package study.eggs.utils;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.util.List;
import java.util.Map;

@Slf4j
public class RestUtils {

    private static final MediaType DEFAULT_MEDIA_TYPE = MediaType.APPLICATION_JSON;

    private static final String EMPTY = "";

    /**
     * 构造URL
     *
     * @param host -String
     * @param path -String
     */
    public static String buildURL(String host, String path) {
        return buildURL(host, path, null);
    }

    /**
     * @param host   -String
     * @param path   -String
     * @param params -Map<String, Object>
     */
    public static String buildURL(String host, String path, Map<String, Object> params) {
        List<String> uri = Lists.newArrayList(host, path);
        if (params == null || params.isEmpty()) {
            return Joiner.on(EMPTY).join(uri);
        }
        String url = Joiner.on(EMPTY)
                .join(uri);
        String query = Joiner.on("&")
                .withKeyValueSeparator("=")
                .join(params);
        return Joiner.on(EMPTY).join(url, "?", query);
    }

    /**
     * 构造Header
     *
     * @param mediaType -MediaType
     */
    public static HttpHeaders buildHeaders(MediaType mediaType) {
        return buildHeaders(mediaType, null);
    }

    /**
     * @param header -Map<String, String>
     */
    public static HttpHeaders buildHeaders(Map<String, String> header) {
        return buildHeaders(DEFAULT_MEDIA_TYPE, header);
    }

    /**
     * @param mediaType -MediaType
     * @param header    -Map<String, String>
     */
    public static HttpHeaders buildHeaders(MediaType mediaType, Map<String, String> header) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);
        if (header != null) {
            header.forEach((k, v) -> {
                headers.set(k, v);
            });
        }
        return headers;
    }

    /**
     * 构造Entity
     *
     * @param body -T
     */
    public static <T> HttpEntity<T> buildEntity(T body) {
        return buildEntity(body, null);
    }

    /**
     * @param header -Map<String, String>
     */
    public static <T> HttpEntity<T> buildEntity(Map<String, String> header) {
        return buildEntity(null, header);
    }

    /**
     * @param body   -T
     * @param header -Map<String, String>
     */
    public static <T> HttpEntity<T> buildEntity(T body, Map<String, String> header) {
        HttpHeaders headers = buildHeaders(header);
        HttpEntity<T> entity = new HttpEntity<>(body, headers);
        return entity;
    }
}
